package com.example.myapplication

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.os.Bundle
import android.text.Spannable
import android.text.method.LinkMovementMethod
import android.text.style.URLSpan
import android.util.Log
import android.view.ActionMode
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.myapplication.databinding.FragmentFirstBinding
import com.example.myapplication.markwon.MarkdownHelper
import com.example.myapplication.mention.packMessageWithMentionSpan
import com.example.myapplication.mention.parseMentionString
import io.noties.markwon.Markwon


/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private val markwon: Markwon by lazy {
        MarkdownHelper.createMarkdownRender(requireContext())
    }

    private val textStr = "# 示例文档\n" +
            "这是一个示例文档，包含一些有用的链接。\n" +
            "如游戏帧绘制，需权衡质量与速度的稳定性" +
            "![](https://cdn.cnbj1.fds.api.mi-img.com/iotweb-product-center/062d569553b9d8fa9e56f392739f6d5d_1752568076519.png?GalaxyAccessKeyId=AKVGLQWBOVIRQ3XLEW&Expires=9223372036854775807&Signature=RWkIU2A3LMua46cjZEgrEvYmZjo=)" +
            "![](https://i-blog.csdnimg.cn/blog_migrate/29d315796eb9a383c98a9ad1a454044f.png)" +
            "图片展示出来了么\n" +
            "## 测试\n" +
            "1. **无顺列表**\n" +
            "2. 你看过[Baidu](https://www.baidu.com) - 百度一下\n" +
            "   - 111111\n" +
            "   - 22222222222222222222222\n" +
            "3. [Hao 123](https://hao123.com) - Hao123\n" +
            "3. 第四行\n" +
            "## 有序列表\n" +
            "- [GitHub](https://github.com) - 代码托管平台\n" +
            "   1. 111111\n" +
            "   2. 22222222222222222222222\n" +
            "- [Google](https://www.google.com) - 搜索引擎\n" +
            "   1. 111111\n" +
            "   2. 222222\n" +
            "- [Baidu](https://www.baidu.com) - 百度一下\n" +
            "   1. 111111\n" +
            "   2. 222222\n" +
            "   3. google\n" +
            "   4. google.com\n" +
            "   5. google.cn\n" +
            "   5. google.cn\n" +
            "   5. google.cn\n" +
            "   5. google.cn\n" +
            "   5. google.cn\n" +
            "   5. google.cn\n" +
            "- [Stack Overflow](https://stackoverflow.com) - 编程问答社区\n" +
            "- [Hao 123](https://hao123.com) - Hao123\n" +
            "---\n" +
            "***\n" +
            ">    这是一个引用\n" +
            "\n\n"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val list = mutableListOf<String>()
        list.add("1")
        list.add("2")
        list.add("3")
        list.add("4")
        val list2 = (list as kotlin.collections.List<String>).reversed()
        val removeLast = list.removeLastOrNull()
        Log.e("tanzhenxing33", "onCreateView:${removeLast}")
        Log.e("tanzhenxing33", "onCreateView:${list}")
        Log.e("tanzhenxing33", "onCreateView:${list2}")
        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.buttonFirst.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }
        binding.textviewFirst.customSelectionActionModeCallback = object : ActionMode.Callback {
            override fun onCreateActionMode(
                mode: ActionMode?,
                menu: Menu?
            ): Boolean {
                return true
            }

            override fun onPrepareActionMode(
                mode: ActionMode?,
                menu: Menu?
            ): Boolean {
                return false
            }

            override fun onActionItemClicked(
                mode: ActionMode?,
                item: MenuItem?
            ): Boolean {
                item?.let {
                    if (item.itemId == android.R.id.copy) {
                        val text = binding.textviewFirst.text.subSequence(binding.textviewFirst.selectionStart, binding.textviewFirst.selectionEnd).toString()
                        // val selection = binding.textviewFirst.selectionStart
                        // val start = text.lastIndexOf("\n", selection)
                        // val end = text.indexOf("\n", selection)
                        // val selectText = text.substring(start + 1, end)
                        val clipboardManager =
                            requireContext().getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                        val clipData = ClipData.newPlainText("text", text)
                        clipboardManager.setPrimaryClip(clipData)
                        Toast.makeText(requireContext(), "复制成功", Toast.LENGTH_SHORT).show()
                        mode?.finish()
                        return true
                    }
                }
                return false
            }

            override fun onDestroyActionMode(mode: ActionMode?) {

            }

        }
        binding.textviewFirst.movementMethod = object : LinkMovementMethod() {
            override fun onTouchEvent(
                widget: TextView,
                buffer: Spannable,
                event: MotionEvent
            ): Boolean {
                if (widget.isTextSelectable) {
                    super.onTouchEvent(widget, buffer, event)
                }
                // 在这里可以处理 URLSpan 点击事件
                val action = event.getAction()
                if (action == MotionEvent.ACTION_UP) {
                    val x = event.getX()
                    val y = event.getY()
                    val offset = widget.getOffsetForPosition(x, y);
                    val link = buffer.getSpans(offset, offset, URLSpan::class.java)
                    if (link.size > 0) {
                        // 如果点击的是 URLSpan，处理点击事件
                        link[0].onClick(widget);
                        return true
                    }
                }
                return false
            }
        }
        markwon.setMarkdown(binding.textviewFirst, textStr)
        binding.textviewFirst2.text = parseMentionString("<at id=\"123\" type=\"device\">小明</at> ，你好！")
        Log.d("tanzhenxing33", "onViewCreated: ${packMessageWithMentionSpan(binding.textviewFirst2.text)}")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}